using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Windows;

namespace WPFTemplateLib.Utilities
{
	/// <summary>
	/// https://www.codeleading.com/article/15213064956/
	/// </summary>
	public static class WindowsMonitorAPI
	{
		private const string User32 = "user32.dll";

		[DllImport(User32, CharSet = CharSet.Auto)]
		[ResourceExposure(ResourceScope.None)]
		public static extern bool GetMonitorInfo(HandleRef hmonitor, [In, Out] MONITORINFOEX info);

		[DllImport(User32, ExactSpelling = true)]
		[ResourceExposure(ResourceScope.None)]
		public static extern bool EnumDisplayMonitors(HandleRef hdc, COMRECT rcClip, MonitorEnumProc lpfnEnum, IntPtr dwData);

		public delegate bool MonitorEnumProc(IntPtr monitor, IntPtr hdc, IntPtr lprcMonitor, IntPtr lParam);

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
		public class MONITORINFOEX
		{
			internal int cbSize = Marshal.SizeOf(typeof(MONITORINFOEX));
			internal RECT rcMonitor = new RECT();
			internal RECT rcWork = new RECT();
			internal int dwFlags = 0;
			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
			internal char[] szDevice = new char[32];
		}

		[StructLayout(LayoutKind.Sequential)]
		public struct RECT
		{
			public int left;
			public int top;
			public int right;
			public int bottom;

			public RECT(Rect r)
			{
				left = (int)r.Left;
				top = (int)r.Top;
				right = (int)r.Right;
				bottom = (int)r.Bottom;
			}
		}

		[StructLayout(LayoutKind.Sequential)]
		public class COMRECT
		{
			public int left;
			public int top;
			public int right;
			public int bottom;
		}

		public static readonly HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
	}
}
